package com.xhb.campusservices.util;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xhb.campusservices.common.lang.Result;
import com.xhb.campusservices.common.lang.ResultCode;
import com.xhb.campusservices.shiro.JwtToken;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.ExpiredCredentialsException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.AuthenticationFilter;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * JWT认证过滤
 */
@Component
public class JWTFilter extends AuthenticationFilter {
    private static final Logger logger = LoggerFactory.getLogger(JWTFilter.class);

    /**
     * 判断是否已认证
     *
     * @param request
     * @param response
     * @param mappedValue
     * @return
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        Subject subject = SecurityUtils.getSubject();
        return null != subject && subject.isAuthenticated();
    }

    /**
     * 认证检查未通过执行该方法
     * 拦截校验，当头部没有Authorization时候，我们直接通过，不需要自动登录；
     * 当带有的时候，首先我们校验jwt的有效性，没问题我们就直接执行executeLogin方法实现自动登录
     *
     * @param request
     * @param response
     * @return
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) {
        //1.检查请求头中是否含有token
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String token = req.getHeader("Authorization");
        //获取当前的url
        String url = String.valueOf(req.getRequestURI());
        //2.如果客户端没有携带token，放行，或者url是登录的路径也给放行
         /*   if (null==token || "".equals(token)|| url.equals("/user/login")
                || url.equals("/user/registered")) {
            return true;
        }*/

        //2.如果客户端没有携带token
        if (null == token || "".equals(token)) {
            return true;
        }

        //3.如果有，对token进行验证
        JwtToken jwtToken = new JwtToken(token);
        try {
            SecurityUtils.getSubject().login(jwtToken);
            //有效令牌，需要重新刷新token，再将token传回客户端，客户端会拿着新的token进行访问
            String newToken = JWTUtils.updateToken(token);
            // System.out.println("newToken:"+newToken);
            resp.setHeader("Authorization", newToken);
            resp.setHeader("Access-Control-Expose-Headers", "Authorization");
        } catch (AuthenticationException e) {
            logger.info("token验证失败！{}", e.getMessage());
            responseTokenError(response, "失败信息:" + e.getMessage());
            throw new ExpiredCredentialsException("token验证失败 ！");
        }
        return true;
    }


    /**
     * 对跨域提供支持
     * 拦截器的前置拦截，因为我们是前后端分析项目，项目中除了需要跨域全局配置之外，
     * 我们再拦截器中也需要提供跨域支持。这样，拦截器才不会在进入Controller之前就被限制了。
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
        //跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }

    /**
     * 返回token认证错误
     *
     * @param response
     * @param msg
     */
    private void responseTokenError(ServletResponse response, String msg) {
        HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json; charset=utf-8");
        try (PrintWriter out = httpServletResponse.getWriter()) {
            ObjectMapper objectMapper = new ObjectMapper();
            String content = objectMapper.writeValueAsString(Result.fail(new ResultCode().getCode(), msg));
            out.append(content);
        } catch (Exception e) {
            logger.error("返回token认证错误信息失败!{}", e.getMessage());
        }
    }

}